<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小企业物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\controller\property\property\users;

use think\App;
use app\controller\property\Base;
use app\validate\property\users\PropertyGroupValidate;
use app\common\repositories\property\group\PropertyGroupRepository;

class PropertyGroup extends Base
{
    protected $repository;

    public function __construct(App $app, PropertyGroupRepository $repository)
    {
        parent::__construct($app);

        $this->repository = $repository;
    }


    /**
     * 职权部门列表
     * @return string|\think\response\Json
     * @throws \Exception
     *
     * @author Amos
     * 2024-01-18 21:32
     */
    public function list()
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'keywords' => '',
            ]);
            [$page, $limit] = $this->getPage();
            $res = $this->repository->getPropertyList($where, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $res['list'], 'count' => $res['count']]);
        } else {
            return $this->fetch('property/group/list', [
                'addAuth' => property_auth('propertyGroupAdd'),
                'editAuth' => property_auth('propertyGroupEdit'),
                'delAuth' => property_auth('propertyGroupDel'),
                'detailAuth' => property_auth('propertyGroupDetail'),

                'addUsersAuth' => property_auth('propertyUsersAdd'),
                'editUsersAuth' => property_auth('propertyUsersEdit'),
                'delUsersAuth' => property_auth('propertyUsersDel'),
                'detailUsersAuth' => property_auth('propertyUsersDetail')
            ]);
        }
    }

    /**
     * 添加职权部门
     * @return string|\think\response\Json|\think\response\View
     * @throws \Exception
     *
     * @author Amos
     * 2024-01-18 17:47
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'name' => '',
                'pid' => '',
                'is_show' => '',
                'remark' => '',
            ]);
            $param['pid'] = (int)$param['pid'];
            validate(PropertyGroupValidate::class)->scene('add')->check($param);
            if ($this->repository->propertyFieldExists($this->request->propertyId, 'name', $param['name'])) {
                return $this->error($param['name'] . ' 已存在');
            }
            try {
                $res = $this->repository->addInfo($param, $this->request->propertyId, $this->request->userId);
                if ($res) {
                    return $this->success('添加成功');
                } else {
                    return $this->error('添加失败');
                }
            } catch (\Exception $e) {
                exception_log('添加职权部门', $e);
                return $this->error('网络错误');
            }
        } else {
            $groupData = $this->repository->getCascaderData(['is_show' => 1]);
            return $this->fetch('property/group/add', [
                'groupData' => $groupData
            ]);
        }
    }


    /**
     * 编辑
     * @return string|\think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-01-17 22:15
     */
    public function edit()
    {
        $id = (int)$this->request->param('id');
        if (!$id) {
            return $this->error('参数错误');
        }
        $info = $this->repository->get($id);
        if (!$info) {
            return $this->error('信息错误');
        }
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'name' => '',
                'pid' => '',
                'is_show' => '',
                'remark' => '',
            ]);
            $param['pid'] = (int)$param['pid'];
            validate(PropertyGroupValidate::class)->scene('edit')->check($param);
            try {
                if ($param['pid'] == $info['id']) {
                    return $this->error('上级部门选择错误');
                }
                if ($param['pid'] && $this->repository->getLevelById($param['pid']) > 3) {
                    return $this->error('超过最大层级');
                }
                if (!$this->repository->checkChangeToChild($info['id'], $param['pid'])) {
                    return $this->error('无法修改到当前分类到子集，请先修改子类');
                }
                if (!$this->repository->checkChildLevel($info['id'], $param['pid'])) {
                    return $this->error('子类超过最低限制，请先修改子类');
                }
                $res = $this->repository->editInfo($info, $param, $this->request->propertyUId);
                if ($res) {
                    return $this->success('修改成功');
                } else {
                    return $this->error('修改失败');
                }
            } catch (\Exception $e) {
                exception_log('编辑职权部门失败', $e);
                return $this->error('网络错误');
            }
        } else {
            $groupData = $this->repository->getCascaderData(['is_show' => 1]);
            return $this->fetch('property/group/edit', [
                'info' => $info,
                'groupData' => $groupData
            ]);

        }
    }

    /**
     * 删除职权部门
     * @return string|\think\response\Json|\think\response\View
     *
     * @author Amos
     * 2024-01-17 22:15
     */
    public function del()
    {
        validate(propertyGroupValidate::class)->scene('del')->check($this->request->param());
        $id = (int)$this->request->param('id');
        $info = $this->repository->get($id);
        if (!$info) {
            return $this->error('信息错误');
        }
        try {
            if ($this->repository->hasChild($id)) {
                return $this->error('该分类存在下级分类，请先处理下级分类');
            }
            $data = $this->repository->deleteInfo($info, $this->request->propertyUId);
            if ($data) {
                return $this->success('删除成功');
            } else {
                return $this->error('删除失败');
            }
        } catch (\Exception $e) {
            exception_log('删除职权部门失败', $e);
            return $this->error('网络错误');
        }
    }


    public function detail()
    {
        $id = (int)$this->request->param('id');
        if ($id <= 0) {
            return $this->error('参数错误');
        }
        $info = $this->repository->getDetail($id);
        if ($info['id'] <= 0) {
            return $this->error('信息不存在');
        }
        return $this->fetch('property/group/detail', [
            'info' => $info,
        ]);
    }

}